package carassius.BLL;

import java.util.Enumeration;
import java.util.HashMap;

/**
 *
 * @author siebz0r
 */
public class HideableListModel<T>
		extends SortedListModel<T>
{
	private HashMap<T, Boolean> _modelItems;

	public HideableListModel()
	{
		super();
		_modelItems = new HashMap<T, Boolean>();
	}

	@Override
	public Enumeration<T> elements()
	{
		return new Enumeration<T>()
		{
			int i = 0;
			final Object[] array = _modelItems.keySet().toArray();

			@Override
			public boolean hasMoreElements()
			{
				return i < array.length;
			}

			@Override
			public T nextElement()
			{
				T o = (T) array[i];
				i++;
				return o;
			}
		};
	}

	@Override
	public void addElement(Object obj)
	{
		_modelItems.put((T) obj, true);
		super.addElement(obj);
	}

	public void addElement(Object obj, boolean visable)
	{
		_modelItems.put((T) obj, visable);
		if (visable)
		{
			super.addElement(obj);
		}
	}

	@Override
	public boolean removeElement(Object obj)
	{
		return _modelItems.remove(obj) && super.removeElement(obj);
	}

	@Override
	public void add(int index, Object element)
	{
		throw new UnsupportedOperationException("Unsupported operation. Use addElement() instead.");
	}

	@Override
	public Object remove(int index)
	{
		throw new UnsupportedOperationException("Unsupported operation. Use removeElement() instead.");
	}

	@Override
	public void removeAllElements()
	{
		clear();
	}

	@Override
	public void removeElementAt(int index)
	{
		Object element = getElementAt(index);
		removeElement(element);
	}

	@Override
	public void removeRange(int fromIndex, int toIndex)
	{
		throw new UnsupportedOperationException("Unsupported operation. Potentially unsafe, use removeElement() or removeElementAt() instead.");
	}

	@Override
	public void clear()
	{
		_modelItems.clear();
		super.clear();
	}

	@Override
	public boolean contains(Object elem)
	{
		return _modelItems.containsKey(elem);
	}

	public void setElementVisible(T obj, boolean visible)
	{
		Boolean previous = _modelItems.get(obj);
		if (previous != null && visible != previous)
		{
			_modelItems.put(obj, visible);
			if (visible)
			{
				super.addElement(obj);
			}
			else
			{
				super.removeElement(obj);
			}
		}
	}

	public void setElementVisibleAll(boolean visible)
	{
		for (T item : _modelItems.keySet())
		{
			setElementVisible(item, visible);
		}
	}
}
